package cn.wx.common.persistence.web;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import cn.wx.common.utils.JSONUtils;
import cn.wx.common.utils.PropertiesUtil;

import java.io.IOException;
import java.util.List;

public class FeignHttpClient {

	/**
	 * 获取当个对象
	 * 
	 * @param url
	 * @param dto
	 * @param clazz
	 * @return
	 */
	public static <E> E postOne(String feignClient, String url, E dto, Class<E> clazz) {
		List<E> list = postList(feignClient, url, dto, clazz);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 发送http post请求 获取list
	 */
	public static <E> List<E> postList(String feignClient, String url, E dto, Class<E> clazz) {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(PropertiesUtil.getProperiesValue(feignClient, "system.properties") + url);
			StringEntity entity = new StringEntity(JSONUtils.c(dto), ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return JSONUtils.pa(resultString, clazz);
	}
}
